﻿using HslCommunication.Profinet.Siemens;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace paraInterface
{
    public class Siemens300PLC_A :PLC//爱谢林箱式炉
    {
        private Dictionary<string, Int16> QuenchingType = new Dictionary<string, Int16> { { "无程序", 0 }, { "缓冷", 3 }, { "无中间冷却油淬火", 9 }, { "带中间冷却油淬火", 10 } };
        Dictionary<string, string> dict = new Dictionary<string, string>();

        public SiemensS7Net SiemensPLC { get; set; }
        public bool isConnected = false;

        byte[] settime = new byte[20];
        short[] tempture = new short[10];
        float[] cp = new float[10];
        ushort[] ts = new ushort[10];
        short[] tempturetol = new short[10];
        float[] cptol = new float[10];
        short[] oil = new short[8];
        ushort cooltype;
        short starttempture;
        float startcp;
        short starttempturetol;
        float startcptol;

        public override bool InitPLC()
        {
            if (IsIP(IP))
            {
                SiemensPLC = new SiemensS7Net(SiemensPLCS.S300, IP);
                SiemensPLC.ConnectTimeOut = 5000;
                for (int i = 1; i <= DATALENTH; i++)
                {
                    dict.Add("B" + i.ToString().PadLeft(3,'0'), "0");
                }
                isRealPLC = true;
            }
            return isRealPLC;
        }
        private bool Connect2PLC()
        {
            if (SiemensPLC == null) return false;
            try
            {
                OperateResult res = SiemensPLC.ConnectServer();
                isConnected = res.IsSuccess;
            }
            catch (Exception)
            {
                isConnected = false;
            }
            if (!isConnected)
                pubcls.WriteLog(IP + "的PLC连接失败！请检查网络或PLC！");
            return isConnected;
        }

        public override bool SendData2PLC(jsonData data)//需要将数据进行解析
        {
            int res = 0;
            if (Connect2PLC())
            {
                try
                {
                    //梳理数据
                    for (int i = 0; i < data.PARAMS.Length; i++)
                    {
                        dict[data.PARAMS[i].TBGD_ITEM_CODE] = data.PARAMS[i].TBGD_UPPER_LIMIT.Trim();
                        if (dict[data.PARAMS[i].TBGD_ITEM_CODE].Length == 0) dict[data.PARAMS[i].TBGD_ITEM_CODE] = "0";
                    }
                    //组织数据进行发送

                    for (int i = 0; i < 10; i++)//必须是10项
                    {
                        //时间14~33  byte 30 ~ 49
                        settime[i * 2] = Convert.ToByte(dict["B" + (15 + i * 2).ToString().PadLeft(3,'0')]);
                        settime[i * 2 + 1] = Convert.ToByte(dict["B" + (15 + i * 2 + 1).ToString().PadLeft(3, '0')]);
                        //温度34~43   INT 50~68
                        tempture[i] = Convert.ToInt16(dict["B" + (35 + i).ToString().PadLeft(3, '0')]);
                        //碳势44~53  REAL 70~106
                        cp[i] = Convert.ToSingle(dict["B" + (45 + i).ToString().PadLeft(3, '0')]);
                        //温度偏差 64~73 INT 130 ~148
                        tempturetol[i] = Convert.ToInt16(dict["B" + (65 + i).ToString().PadLeft(3, '0')]);
                        //碳势偏差 74~83  REAL 150 ~186
                        cptol[i] = Convert.ToSingle(dict["B" + (75 + i).ToString().PadLeft(3, '0')]);

                        //StringBuilder bints = new StringBuilder("0000000000000000");
                        //for (int j = 0; j < 6; j++)
                        //{
                        //    bints[7 - j] = (grd_Editor.Rows[i].Cells[j + 7].Value.ToString().Trim() == "" || grd_Editor.Rows[i].Cells[j + 7].Value.ToString().Trim() == "0") ? '0' : '1';
                        //}
                        //ts[i] = Convert.ToUInt16(bints.ToString(), 2);
                        //ts 54~63 ushort 110~128,注意，需要事先在过来的数据上进行组合成无符号整数
                        ts[i] = Convert.ToUInt16(dict["B" + (55 + i).ToString().PadLeft(3, '0')]);
                    }
                    //short cooltype = QuenchingType[cmb_QuenchingType.Text];
                    cooltype = Convert.ToUInt16(dict["B007"]);
                    starttempture = Convert.ToInt16(dict["B010"]);
                    startcp = Convert.ToSingle(dict["B011"]);
                    starttempturetol = Convert.ToInt16(dict["B012"]);
                    startcptol = Convert.ToSingle(dict["B013"]);
                    for (int i = 0; i < 8; i++)
                    {
                        oil[i] = Convert.ToInt16(dict["B" + (92 + i).ToString().PadLeft(3, '0')]);

                    }
                    //oil[1] = Convert.ToInt16(textBox6.Text);
                    //oil[2] = Convert.ToInt16(textBox7.Text);
                    //oil[3] = Convert.ToInt16(textBox8.Text);
                    //oil[4] = Convert.ToInt16(textBox9.Text);
                    //oil[5] = Convert.ToInt16(textBox10.Text);
                    //oil[6] = Convert.ToInt16(textBox11.Text);
                    //oil[7] = Convert.ToInt16(textBox12.Text);

                    res += SiemensPLC.Write(ADD + ".10", cooltype).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".16", starttempture).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".18", startcp).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".22", starttempturetol).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".24", startcptol).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".30", settime).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".50", tempture).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".70", cp).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".110", ts).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".130", tempturetol).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".150", cptol).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".204", oil).IsSuccess ? 0 : 1;
                    res += SiemensPLC.Write(ADD + ".220", (short)1).IsSuccess ? 0 : 1;

                }
                catch (Exception)
                {
                    res = 1000;
                }
            }
            else
            {
                res = 1000;
            }
            SiemensPLC.ConnectClose();
            return (res == 0 ? true : false);
        }
        public bool ComfirmProgramDataFromPLC()
        {
            try
            {
                if (Connect2PLC())
                {
                    short _cooltype = SiemensPLC.ReadInt16(ADD + ".10").Content;
                    short _starttempture = SiemensPLC.ReadInt16(ADD + ".16").Content;
                    float _startcp = SiemensPLC.ReadFloat(ADD + ".18").Content;
                    short _starttempturetol = SiemensPLC.ReadInt16(ADD + ".22").Content;
                    float _startcptol = SiemensPLC.ReadFloat(ADD + ".24").Content;
                    byte[] _settime = SiemensPLC.Read(ADD + ".30", 20).Content;
                    short[] _tempture = SiemensPLC.ReadInt16(ADD + ".50", 10).Content;
                    float[] _cp = SiemensPLC.ReadFloat(ADD + ".70", 10).Content;
                    ushort[] _ts = SiemensPLC.ReadUInt16(ADD + ".110", 10).Content;
                    short[] _tempturetol = SiemensPLC.ReadInt16(ADD + ".130", 10).Content;
                    float[] _cptol = SiemensPLC.ReadFloat(ADD + ".150", 10).Content;
                    short[] _oil = SiemensPLC.ReadInt16(ADD + ".204", 8).Content;

                    SiemensPLC.ConnectClose();

                    if (_cooltype != cooltype) return false;
                    if (_starttempture != starttempture) return false;
                    if (_startcp != startcp) return false;
                    if (_starttempturetol != starttempturetol) return false;
                    if (_startcptol != startcptol) return false;
                    for (int i = 0; i < 8; i++)
                    {
                        if (_oil[i] != oil[i]) return false;
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        if (_settime[i * 2] != settime[i * 2]) return false;//小时
                        if (_settime[i * 2 + 1] != settime[i * 2 + 1]) return false;//分钟
                        if (_tempture[i] != tempture[i]) return false;//温度
                        if (_cp[i] != cp[i]) return false;//碳势
                        if (_tempturetol[i] != tempturetol[i]) return false;//温度偏差
                        if (_cptol[i] != cptol[i]) return false;//碳势偏差

                        return true;
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
        private string GetQuenchingTyepByValue(int v)
        {
            foreach (string item in QuenchingType.Keys)
            {
                if (QuenchingType[item] == v) return item;
            }
            return "";
        }
    }
}
